package mybatisflex.codegen.factory;

import com.mybatisflex.codegen.config.EntityConfig;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.config.PackageConfig;
import com.mybatisflex.codegen.entity.Table;
import com.mybatisflex.codegen.generator.IGenerator;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刁海文
 * @Remark
 * @since 2023/7/19 15:39
 */
public class MapstructGenerator implements IGenerator {
    private String templatePath = "/templates/enjoy/mapstruct.tpl";

    private final String suffix;
    private final String pk;
    public MapstructGenerator(String suffix, String pk) {
        this.suffix = suffix;
        this.pk = pk;
    }

    @Override
    public String getTemplatePath() {
        return templatePath;
    }

    @Override
    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }

    @Override
    public void generate(Table table, GlobalConfig globalConfig) {



        PackageConfig packageConfig = globalConfig.getPackageConfig();
        EntityConfig entityConfig = globalConfig.getEntityConfig();
        String entityName = table.getEntityJavaFileName() + suffix;
        String packageName = globalConfig.getBasePackage() + "." + pk;

        String entityPackagePath = packageName.replace(".", File.separator) + File.separator + entityName + ".java";
        File entityJavaFile = new File(packageConfig.getSourceDir(), entityPackagePath);


        if (entityJavaFile.exists() && !entityConfig.isOverwriteEnable()) {
            return;
        }



        entityConfig.setAlwaysGenColumnAnnotation(false);
        Map<String, Object> params = new HashMap<>(6);
        params.put("table", table);
        params.put("entityPackageName", packageName);
        params.put("entityConfig", entityConfig);
        params.put("entityClassName", entityName);
        params.put("packageConfig", packageConfig);
        params.put("javadocConfig", globalConfig.getJavadocConfig());
        params.put("queryEntity", table.buildEntityClassName().replace("DO", "Query"));
        params.put("dtoEntity", table.buildEntityClassName().replace("DO", "DTO"));
        String qpk = globalConfig.getBasePackage() + ".obj.query";
        String dpk = globalConfig.getBasePackage() + ".obj.dto";
        params.put("dtoPk", dpk);
        params.put("queryPk", qpk);

        globalConfig.getTemplateConfig().getTemplate().generate(params, templatePath, entityJavaFile);

        System.out.println("Entity ---> " + entityJavaFile);
        entityConfig.setAlwaysGenColumnAnnotation(true);

    }
}
